package com.plugin;

import com.edu.HandlerDefinition;
import com.edu.factory.HandlerFactory;
import demo.bean.BeanFactory;
import demo.bean.annotations.Component;

import java.lang.reflect.Method;

public class ContainerHandlerFactory implements HandlerFactory {

    private BeanFactory beanFactory;

    public ContainerHandlerFactory(BeanFactory beanFactory){
        this.beanFactory = beanFactory;
    }

    public BeanFactory getBeanFactory(){
        return beanFactory;
    }

    @Override
    public Object createHandler(HandlerDefinition definition){
        if (definition!=null){
            Method method = definition.getMethod();
            if (method!=null){
                return beanFactory.getBean(getBeanName(method));
            }
        }
        return null;
    }

    protected String getBeanName(Method method) {
        String value = null;
        if (method.getDeclaringClass().getAnnotation(Component.class)!=null){
            value = method.getDeclaringClass().getAnnotation(Component.class).value();
            value = ("".equals(value))? BeanNameUtil.toLowerBeanName(method.getDeclaringClass().getSimpleName()):value;
        }
        return value;
    }
}
